/*
 * Copyright 2015-2016 Tumblr, Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tumblr.backboard.imitator;

import com.facebook.rebound.Spring;
import ohos.agp.components.Component;
import ohos.multimodalinput.event.TouchEvent;

/**
 * Toggle between two Spring states depending on whether or not the user is touching the screen. When the user presses,
 * TouchEvent is called and the active value is set. When the user releases, TouchEvent is called and the rest value is
 * set.
 *
 * @author ericleong
 * @since 2021-05-07
 */
public class ToggleImitator extends EventImitator implements Component.TouchEventListener {
    private double mActiveValue;

    /**
     * Constructor. It is necessary to call {@link #setSpring(Spring)} to set the spring.
     *
     * @param spring the spring to use.
     * @param restValue the value when off.
     * @param activeValue the value when on.
     */
    public ToggleImitator(Spring spring, double restValue, double activeValue) {
        super(spring, restValue, TRACK_ABSOLUTE, FOLLOW_EXACT);
        mActiveValue = activeValue;
    }

    @Override
    public void constrain(TouchEvent event) {
        mSpring.setEndValue(mActiveValue);
    }

    @Override
    protected double mapToSpring(float motionValue) {
        // not used
        return mActiveValue;
    }

    @Override
    public boolean onTouchEvent(Component v, TouchEvent event) {
        imitate(v, event);

        return true;
    }

    @Override
    public void imitate(Component view, TouchEvent event) {
        switch (event.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                constrain(event);
                break;

            case TouchEvent.CANCEL:
            case TouchEvent.PRIMARY_POINT_UP:
                release(event);
                break;

            default:
        }
    }
}
